package com.example.demo.Service.Impl;

import com.example.demo.Dao.ProductMapper;
import com.example.demo.Entity.Product;
import com.example.demo.Service.ProductService;
import com.example.demo.Util.BeanUtil;
import com.example.demo.Util.PageQueryUtil;
import com.example.demo.Util.PageResult;
import com.example.demo.VO.SearchProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Product getProductById(Long id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult searchProducts(PageQueryUtil pageUtil) {
        List<Product> productList = productMapper.findProductsListBySearch(pageUtil);
        int total = productMapper.getTotalProductsBySearch(pageUtil);
        List<SearchProductVO> searchProductsVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productList)) {
            searchProductsVOS = BeanUtil.copyList(productList, SearchProductVO.class);
            for (SearchProductVO searchProductVO : searchProductsVOS) {
                String productName = searchProductVO.getProductName();
                String productIntro = searchProductVO.getProductIntro();
                // 字符串过长导致文字超出的问题
                if (productName.length() > 28) {
                    productName = productName.substring(0, 28) + "...";
                    searchProductVO.setProductName(productName);
                }
                if (productIntro.length() > 30) {
                    productIntro = productIntro.substring(0, 30) + "...";
                    searchProductVO.setProductIntro(productIntro);
                }
            }
        }
        PageResult pageResult = new PageResult(searchProductsVOS, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public Product getProductByProducName(String productname) {
        return this.productMapper.selectByProductName(productname);
    }
}
